<template>
    <!-- use the modal component, pass in the prop -->
    <modal v-if="stateManager.ImportDialogVisible"
           @cancel="closeDialog"
           @ok="saveModel"
           :modal-title="modalTitle"
           model-size="normal">
        <!--
          you can use custom content here to overwrite
          default content
        -->
        <vue-form>
            <div class="row">

                <div class="col-xs-12" v-if="!loading">
                    <vue-form-item label="上传音频">
                        <VueUpload :size="1024" accept="audio/mpeg,audio/x-ms-wma, audio/x-wav"
                                   @input="fileChange" class="btn btn-primary btn-xs"> {{model.file_name}}
                        </VueUpload>
                        <br>
                        <span class="text-danger">允许上传类型：“.mp3 .wma .wav”</span>
                    </vue-form-item>
                </div>
                <audio id="audio" controls="" style="display: none;">

                </audio>
                <div class="col-xs-12" v-if="loading">
                    <div class="spiner-example">
                        <div class="sk-spinner sk-spinner-cube-grid">
                            <div class="sk-cube"></div>
                            <div class="sk-cube"></div>
                            <div class="sk-cube"></div>
                            <div class="sk-cube"></div>
                            <div class="sk-cube"></div>
                            <div class="sk-cube"></div>
                            <div class="sk-cube"></div>
                            <div class="sk-cube"></div>
                            <div class="sk-cube"></div>
                        </div>
                    </div>
                </div>
            </div>
        </vue-form>
    </modal>

</template>

<script>
    import VueUpload from 'vue-upload-component';

    export default {
        props: {
            stateManager: {
                type: Object
            }
        },
        data: function () {
            return {
                loading: false,
                time:0,
                model: this.$modelDataSource({
                    url: 'wechat/VoiceUpload',
                    dataKey: 'model',
                    attributes: {
                        file: '',
                        file_name: '请选择文件',
                    }
                })
            };
        },
        methods: {
            closeDialog: function () {
//                console.log(11);
                if (this.loading == false) {
                    this.model.reset();
                    this.stateManager.ImportDialogVisible = false;
                }

            },
            fileChange(file) {
                let objUrl = this.getObjectURL(file[0].file);
                $('#audio').attr('src',objUrl);
                this.getTime();
               // console.log($('#audio')[0].duration());
                // console.log(file[0].file.size);
                if (file[0].file.size > (4 * 1024000)) {
                    toastr.error('请上传4M以下的文件');
                }else if(!this.checkName(file[0].file.name)){
                    toastr.error('音频格式有误');
                } else {
                    this.model.file = file[0].file;
                    this.model.file_name = file[0].name;
                }
            },
            checkName:function (name) {
                return /^(.+?)\.(mp3|wma|wav|amr|MP3|WMA|WAV|AMR)$/.test(name);
            },
           getTime : function() {
                let _this=this;
                setTimeout(function () {
                    let duration = $("#audio")[0].duration;
                    if(isNaN(duration)){
                      //  console.log(duration);
                        _this.getTime();
                    }
                    else{
                      //  console.log(duration);
                        if(duration>60){
                            _this.model.file ='';
                            _this.model.file_name = '请选择文件';
                            toastr.error('请上传时长不超过60s的文件');
                        }
                    }
                }, 10);
            },
            getObjectURL: function (file) {
                let url = null;
                if (window.createObjectURL != undefined) { // basic
                    url = window.createObjectURL(file);
                } else if (window.URL != undefined) { // mozilla(firefox)
                    url = window.URL.createObjectURL(file);
                } else if (window.webkitURL != undefined) { // webkit or chrome
                    url = window.webkitURL.createObjectURL(file);
                }
                return url;
            },
            saveModel: function () {
                let self = this;
                if (self.model.file != '') {
                    self.validate(function () {
                        self.loading = true;
                        let formData = new FormData();
                        formData.append('file', self.model.file);
                        formData.append('file_name', self.model.file_name);
                        let config = {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }
                        axios.post('wechat/VoiceUpload', formData, config).then(function (res) {
                            self.stateManager.refreshList = true;
                            self.loading = false;
                            self.closeDialog();
                            toastr.success('上传成功！');
                        }).catch(function (res) {
                            console.log(res);
                            self.loading = false;
                            self.stateManager.refreshList = true;
                            toastr.error('上传失败');
                        })
                    })
                }
//                ladda.start();
            },
            validate: function (successCallback, failedCallback) {
                this.$validator.validateAll().then(() => {
                    // eslint-disable-next-line
                    console.log('验证通过');
                    typeof successCallback === 'function' && successCallback();
                }).catch(() => {
                    // eslint-disable-next-line
                    console.log('验证未通过');
                    typeof failedCallback === 'function' && failedCallback();
                });

            }
        },
        computed: {
            modalTitle: function () {
                return '音频上传';
            }
        },
        components: {
            VueUpload
        }
    }
</script>
